package com.howells.time.module.main.view;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.astuetz.PagerSlidingTabStrip;
import com.howells.time.R;
import com.howells.time.base.activity.BaseActivity;
import com.howells.time.base.adapters.ViewPagerAdapter;
import com.howells.time.base.utils.SharedPrefsUtil;
import com.howells.time.base.utils.ToastShow;
import com.howells.time.module.UIHelper;
import com.howells.time.module.discovery.view.DiscoveryFragment;
import com.howells.time.module.main.model.User;
import com.howells.time.module.main.presenter.MainPresenter;
import com.howells.time.module.main.presenter.MainPresenterImp;
import com.howells.time.module.message.view.MessageFragment;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.Eases.EaseType;
import com.nightonke.boommenu.Types.BoomType;
import com.nightonke.boommenu.Types.ButtonType;
import com.nightonke.boommenu.Types.ClickEffectType;
import com.nightonke.boommenu.Types.DimType;
import com.nightonke.boommenu.Types.OrderType;
import com.nightonke.boommenu.Types.PlaceType;
import com.nightonke.boommenu.Util;
import com.orhanobut.logger.Logger;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class MainActivity extends BaseActivity
        implements
        NavigationView.OnNavigationItemSelectedListener,
        BoomMenuButton.OnSubButtonClickListener,
        MainView {

    private ViewPager pager;
    private PagerSlidingTabStrip mTab;
    private ViewPagerAdapter mAdapter;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private View viewhead;
    private BoomMenuButton boomMenuButton;

    public static User user;
    private MainPresenter mainPresenter;

    private DiscoveryFragment discoveryFragment;
    private MessageFragment followFragment;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent().getIntExtra("main", 0) == 1) {
            UIHelper.jumpLogin(this);
        }


        setContentView(R.layout.activity_main);

        initViewPagers();
        init();

        boomMenuButton = (BoomMenuButton) findViewById(R.id.boom);

        mainPresenter = new MainPresenterImp(this);
        mainPresenter.getUserInfo();
        updateinfo();
/*
        boolean openservice= SharedPrefsUtil.getValue(getApplicationContext(),"config","service",true);
        if(openservice){
            startService(new Intent(this, TimeService.class));
        }*/

        //自动刷新列表
        //discoveryFragment.timerstart();
    }

    private void initViewPagers() {
        discoveryFragment = new DiscoveryFragment();
        mFragments.add(discoveryFragment);
        followFragment = new MessageFragment();
        mFragments.add(followFragment);


        mAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragments);
        pager = (ViewPager) findViewById(R.id.viewpager);
        mTab = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        pager.setAdapter(mAdapter);
        mTab.setViewPager(pager);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        int[][] subButtonColors = new int[3][2];
        for (int i = 0; i < 3; i++) {
            subButtonColors[i][1] = ContextCompat.getColor(this, R.color.grey);
            subButtonColors[i][0] = Util.getInstance().getPressedColor(subButtonColors[i][1]);
        }
        new BoomMenuButton.Builder()
                // set all sub buttons with subButtons method
                //.subButtons(subButtonDrawables, subButtonColors, subButtonTexts)
                // or add each sub button with addSubButton method
                .addSubButton(this, R.drawable.refresh, subButtonColors[0], "刷新")
                .addSubButton(this, R.drawable.mark, subButtonColors[1], "停止")
                .addSubButton(this, R.drawable.copy, subButtonColors[2], "小视频")
                .frames(80)
                .duration(100)
                .delay(100)
                .showOrder(OrderType.RANDOM)
                .hideOrder(OrderType.RANDOM)
                .button(ButtonType.CIRCLE)
                .boom(BoomType.PARABOLA_2)
                .place(PlaceType.CIRCLE_3_3)
                .showMoveEase(EaseType.EaseOutBack)
                .hideMoveEase(EaseType.EaseOutCirc)
                .showScaleEase(EaseType.EaseOutBack)
                .hideScaleType(EaseType.EaseOutCirc)
                .rotateDegree(720)
                .showRotateEase(EaseType.EaseOutBack)
                .hideRotateType(EaseType.Linear)
                .autoDismiss(true)
                .cancelable(true)
                .dim(DimType.DIM_6)
                .clickEffect(ClickEffectType.RIPPLE)
                .boomButtonShadow(Util.getInstance().dp2px(2), Util.getInstance().dp2px(2))
                .subButtonsShadow(Util.getInstance().dp2px(2), Util.getInstance().dp2px(2))
                .subButtonTextColor(Color.BLACK)
                .onBoomButtonBlick(null)
                .animator(null)
                .onSubButtonClick(this)
                // this only work when the place type is SHARE_X_X
                .shareStyle(0, 0, 0)
                .init(boomMenuButton);
    }

    private void init() {

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        viewhead = navigationView.getHeaderView(0);
        viewhead.findViewById(R.id.image_head).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UIHelper.jumpUpdateInfo(MainActivity.this);
            }
        });
    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (System.currentTimeMillis() - exitTime > 2000) {
                ToastShow.ToastShort(this, "再按一次退出");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
        }
    }


    //侧滑点击事件
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        switch (id) {
            case R.id.nav_me:
                Toast.makeText(this, "我的", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_drafts:
                Toast.makeText(this, "草稿箱", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_like:
                Toast.makeText(this, "赞", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_comment:
                Toast.makeText(this, "评论", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_account:
                UIHelper.jumpAccount(this);
                break;
            case R.id.nav_setting:
                UIHelper.jumpSetting(this);
                break;
            case R.id.nav_about:
                UIHelper.jumpAbout(this);
                break;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  //      drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void saveInfo(Map<String, Object> info) {
        user = new User();
        user.setId(info.get("id").toString());
        user.setAddress(info.get("address").toString());
        user.setAutograph(info.get("autograph").toString());
        user.setName(info.get("name").toString());
        user.setLogoid(info.get("logoid").toString());
        SharedPrefsUtil.putValue(this, "UserInfo", "id", user.getId());
        SharedPrefsUtil.putValue(this, "UserInfo", "address", user.getAddress());
        SharedPrefsUtil.putValue(this, "UserInfo", "autograph", user.getAutograph());
        SharedPrefsUtil.putValue(this, "UserInfo", "name", user.getName());
        SharedPrefsUtil.putValue(this, "UserInfo", "logoid", user.getLogoid());
        mainPresenter.getHead(user.getLogoid());

    }

    @Override
    public void saveHeadImage(String path) {
        SharedPrefsUtil.putValue(this, "UserInfo", "logopath", path);
        updateinfo();
    }

    @Override
    public void shakeAction() {
        ToastShow.ToastShort(this, "刷新成功");
    }

    private void updateinfo() {
        TextView textname = (TextView) viewhead.findViewById(R.id.text_name);
        ImageView headImage = (ImageView) viewhead.findViewById(R.id.image_head);

        textname.setText(SharedPrefsUtil.getValue(this, "UserInfo", "name", "null***"));
        String path = SharedPrefsUtil.getValue(this, "UserInfo", "logopath", "touxiang.png");
        Bitmap bitmap = null;
        try {
            FileInputStream fis = new FileInputStream(path);
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            //     e.printStackTrace();
            Log.d("MainActivity", "未找到图片");
        }
        if (bitmap != null)
            headImage.setImageBitmap(bitmap);
    }

    public void onClick(View view) {
        switch (view.getId()) {
       /*     case R.id.fab:
                UIHelper.jumpNewvideo(this);
                break;*/

        }
    }

    @Override
    public void onClick(int buttonIndex) {
        switch (buttonIndex){
            case 0:
                discoveryFragment.timerstart();
                break;
            case 1:
                discoveryFragment.timerstop();
                break;
            case 2:
                UIHelper.jumpNewvideo(this);
                break;
        }
    }



}
